package com.atguigu.shrio.realm;

import com.atguigu.shrio.domain.Account;
import com.atguigu.shrio.service.AccountService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;


/**
 * @PROJECT_NAME: shrio
 * @DESCRIPTION:
 * @USER: 28416
 * @DATE: 2022/11/15 12:25
 *
 *
 * 权限判断
 */
public class AccountRealm  extends AuthorizingRealm {

    @Autowired
    private AccountService accountService;
    /**
     * 授权  登录后
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前当前登录的用户信息

        Subject subject = SecurityUtils.getSubject();
        Account account = (Account) subject.getPrincipal();
        HashSet<String> strings = new HashSet<>();
        strings.add(account.getRole());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission(account.getPerms());
        return info;
    }

    /**
     * 认证  登录前
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        Account account = accountService.findByUsername(token.getUsername());
        if (account != null) {
            return new SimpleAuthenticationInfo(account,account.getPassword(),getName());
        }
        return null;
    }
}
